package com.xyzwps.ewa.modules.user

import com.xyzwps.ewa.common.Page
import com.xyzwps.ewa.common.Pager
import kotlin.math.ceil


object UserService {

    fun create(user: UserInfoForCreating): User {
        val newUser = User(UserId.IGNORED, user.name, user.gender, UserState.ACTIVE)
        val userId = UserRepository.create(newUser)
        return UserRepository.read(userId)!!
    }

    fun read(id: UserId): User? = UserRepository.read(id)

    fun read(page:Page): Pager<User> {
        val (pageNo, pageSize) = page
        val count = UserRepository.count()
        val data = UserRepository.findByPage(pageNo, pageSize)
        return Pager(
            data = data,
            pageNo = pageNo,
            pageSize = pageSize,
            pageCount = ceil(count * 0.1 / pageSize).toInt(),
            totalCount = count,
        )
    }

    fun update(userId: UserId, user: UserInfoForUpdating): User? {
        val oldUser = UserRepository.read(userId) ?: return null
        val toSave = oldUser.copy(name = user.name, gender = user.gender)
        UserRepository.update(toSave)
        return toSave
    }

    fun delete(id: UserId): Unit = UserRepository.delete(id)
}

